#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

using System.Web;

using System.Collections;
using WaveMaster.Holidays.Club.Domain;
using WaveMaster.Holidays.Club.Service;

#endregion

namespace WaveMaster.Holidays.Club.Web
{
    public partial class TicketPurchaseForm : Form
    {
        TicketPurchase m_ticketPurchase;
        User m_current_user;
        EditMode m_editmode;
        TicketPurchaseService m_ticketPurchaseService;
        MemberTypeService m_MemberTypeService;
        TravelAgentService m_TravelAgentService;
        MainForm m_mainForm;
        UserControlTicketPurchase m_parentForm;

        public TicketPurchaseForm(string name, TicketPurchase user, User currentUser, MainForm mainForm, UserControlTicketPurchase parentForm, EditMode editmode)
        {
            InitializeComponent();
            m_ticketPurchaseService = (TicketPurchaseService)ServiceFactory.Instance().GetService(ServiceFactory.TICKET_PURCHASE_SERVICE);
            m_TravelAgentService = (TravelAgentService)ServiceFactory.Instance().GetService(ServiceFactory.TRAVEL_AGENT_SERVICE);
            m_MemberTypeService = (MemberTypeService)ServiceFactory.Instance().GetService(ServiceFactory.MEMBER_TYPE_SERVICE);
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            m_ticketPurchase = user;
            initButtonEvent();
            initComboDataSource();
            setEditMode(editmode);
            if (user.PurchaseID == 0)
            {
                clearForm();
            }
            else
            {
                m_ticketPurchase = m_ticketPurchaseService.GetTicketPurchaseByID(user.PurchaseID);
                loadUser(); 
                enableForm(editmode == EditMode.Edit);
            }
            
            //enableForm(false);
           
        }

        private void clearForm()
        {
            textBoxUserCode.Text = "AUTONUMBER";
            dateTimePickerDate.Value = DateTime.Today;
            numericUpDownTotalAmount.Value = 1;
            comboBoxTravelAgent.SelectedIndex = 0;
            comboBoxTicketType.Text = TicketType.TwoWay.ToString();
            numericUpDownQuantity.Value =1;
            numericUpDownUnitPrice.Value = 1;
            m_ticketPurchase = new TicketPurchase();
            clearErrorProvider();
            enableForm(true);
            setEditMode(EditMode.Create);
            textBoxUserCode.SelectAll();
            //comboBoxTravelAgent.Focus();
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }
              
        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            setEditMode(EditMode.Edit);
            enableForm(!toolBarButtonEdit.Enabled);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
            MessageBox.Show("Are you sure to cancel?", "Confirmation", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
             MessageBoxWindow msg = (MessageBoxWindow)sender;
             if (msg.DialogResult == DialogResult.Yes)
             {
                 this.Close();
             }
        }
        private void initComboDataSource()
        {
            comboBoxTravelAgent.DataSource = m_TravelAgentService.LoadAllTravelAgent();
            comboBoxTicketType.DataSource = Enum.GetValues(typeof(TicketType));
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadUser();
        }

        private void clearErrorProvider()
        {
            errorProviderUser.SetError(textBoxUserCode, "");
            errorProviderUser.SetError(numericUpDownQuantity, "");
            errorProviderUser.SetError(numericUpDownUnitPrice, "");
            errorProviderUser.SetError(comboBoxTravelAgent, "");
        }
        private bool isValidForm()
        {
            clearErrorProvider();
            bool valid_a = textBoxUserCode.Text != string.Empty;
            bool valid_b = numericUpDownQuantity.Value != 0;
            bool valid_c = numericUpDownUnitPrice.Value != 0;
            bool valid_d = comboBoxTravelAgent.SelectedItem != null;
            if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "Code can not be empty");
            if (!valid_b) errorProviderUser.SetError(numericUpDownQuantity, "Quantity can not be empty");
            if (!valid_c) errorProviderUser.SetError(numericUpDownUnitPrice, "Unit Price can not be empty");
            if (!valid_d) errorProviderUser.SetError(comboBoxTravelAgent, "Travel Agent can not be empty");
            return valid_b && valid_c && valid_d;
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_ticketPurchase.Code = textBoxUserCode.Text;
                    m_ticketPurchase.TransactionDate = dateTimePickerDate.Value; ;
                    m_ticketPurchase.Quantity = numericUpDownQuantity.Value;
                    m_ticketPurchase.UnitPrice = numericUpDownUnitPrice.Value;
                    m_ticketPurchase.TravelAgent = (TravelAgent)comboBoxTravelAgent.SelectedItem;
                    m_ticketPurchase.TicketType = (TicketType)Enum.Parse(typeof(TicketType), comboBoxTicketType.Text);
                    //update discount
                    m_ticketPurchase.TravelAgent.MemberType = m_MemberTypeService.GetMemberTypeByID( m_ticketPurchase.TravelAgent.MemberType.m_member_type_id);
                    m_ticketPurchase.Discount = m_ticketPurchase.TravelAgent.MemberType.m_discount;
                    //--------------
                    if (m_ticketPurchase.PurchaseID > 0)
                    {
                        m_ticketPurchase.ModificationBy = m_current_user.UserID;
                        m_ticketPurchaseService.UpdateTicketPurchase(m_ticketPurchase);
                    }
                    else
                    {
                        m_ticketPurchase.CreatenBy = m_current_user.UserID;
                        m_ticketPurchaseService.InserTicketPurchase(m_ticketPurchase);
                    }
                    m_parentForm.LoadAllTicketPurchase();
                  //  MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("Record has been saved [" + m_ticketPurchase.Code + "].", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                   // this.Close();
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }

        void closeForm(object sender, EventArgs e)
        {
            this.Close();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete)&& m_current_user.RoleDetails(this.Name).NewFlag;

            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.RoleDetails(this.Name).UpdateFlag;
           
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        private void enableForm(bool enable)
        {
            textBoxUserCode.ReadOnly = !enable;
            comboBoxTravelAgent.Enabled = enable && m_ticketPurchase.PurchaseID == 0;
            numericUpDownQuantity.Enabled = enable;
            numericUpDownUnitPrice.Enabled = enable;
            //numericUpDownTotalAmount.ReadOnly = !enable;
            comboBoxTicketType.Enabled = enable;
            dateTimePickerDate.Enabled = enable;
        }

        private void loadUser()
        {
            m_ticketPurchase.TravelAgent = m_TravelAgentService.GetTravelAgentByID(m_ticketPurchase.TravelAgent.TravelAgentID);

            textBoxUserCode.Text = m_ticketPurchase.Code;
            numericUpDownTotalAmount.Value = m_ticketPurchase.TotalAmount;
            comboBoxTravelAgent.Text = m_ticketPurchase.TravelAgent.ToString();
            numericUpDownQuantity.Value = m_ticketPurchase.Quantity;
            numericUpDownUnitPrice.Value = m_ticketPurchase.UnitPrice;
            comboBoxTicketType.Text = m_ticketPurchase.TicketType.ToString();
            dateTimePickerDate.Value = m_ticketPurchase.TransactionDate;
            labelDisc.Text = m_ticketPurchase.Discount.ToString();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void comboBoxTravelAgent_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_ticketPurchase.PurchaseID > 0 || !toolBarButtonSave.Enabled)
            {
                labelNote.Text = "";
                return;
            }
            
            if (comboBoxTravelAgent.SelectedValue == null) return;
            TravelAgent ta = (TravelAgent)comboBoxTravelAgent.SelectedValue;
            ta.MemberType = m_MemberTypeService.GetMemberTypeByID(ta.MemberType.m_member_type_id);
            int tr = m_ticketPurchaseService.SearchTicketPurchaseByAgent(ta.TravelAgentID);
            if (tr == 0)
            {
                labelNote.Text = "New Member";
                

                //if (ta.MemberTypeEnum == MemberTypeEnum.Gold)
                //{
                //    numericUpDownQuantity.Value = ta.MemberType.m_price; //100;
                //    numericUpDownUnitPrice.Value = 30;
                //}
                //else
                //{
                //    numericUpDownQuantity.Value = 20;
                //    numericUpDownUnitPrice.Value = 20;
                //}
                comboBoxTicketType.Text = TicketType.TwoWay.ToString();
                //numericUpDownQuantity.Enabled = false;
               // numericUpDownQuantity.ReadOnly = true;
                //comboBoxTicketType.Enabled = false;
            }
            else
            {
                labelNote.Text = "Top Up Ticket";
                //numericUpDownQuantity.Enabled = true;
                //numericUpDownQuantity.ReadOnly = false;
                //comboBoxTicketType.Enabled = false;
            }
            numericUpDownQuantity.Value = 100;
            numericUpDownUnitPrice.Value = ta.MemberType.m_price; //30;
            labelDisc.Text = ta.MemberType.m_discount.ToString();
        }

        private void numericUpDownQuantity_ValueChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount();
        }

        private void CalculateTotalAmount()
        {
            if (toolBarButtonSave.Enabled)
            {
                if (comboBoxTravelAgent.SelectedValue == null) return;
                TravelAgent ta = (TravelAgent)comboBoxTravelAgent.SelectedValue;
                ta.MemberType = m_MemberTypeService.GetMemberTypeByID(ta.MemberType.m_member_type_id);
                decimal totalAmount = numericUpDownQuantity.Value * numericUpDownUnitPrice.Value;
                decimal discount = ta.MemberType.m_discount * totalAmount / 100;
                numericUpDownTotalAmount.Value = totalAmount - discount;
            }
        }

        private void numericUpDownUnitPrice_ValueChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount();
        }
    }
}